package com.bifrost.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bifrost.common.constant.SessionConstant;
import com.bifrost.entity.MerchantStore;
import com.bifrost.entity.Order;
import com.bifrost.entity.OrderReturn;
import com.bifrost.model.cbmember.JudgeReturnRequest;
import com.bifrost.repository.OrderReturnRepository;
import com.bifrost.service.MemberService;
import com.bifrost.util.EncryptUtils;
import com.bifrost.util.HttpClientUtil;
import com.bifrost.util.HttpContextUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import java.net.HttpCookie;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author rangf
 * @date 2018/3/9
 */
@Service
public class MemberServiceImpl implements MemberService {

    private Logger logger = LoggerFactory.getLogger(MemberService.class);

    @Value("${cbest.member.info.url:#{null}}")
    private String infoApi;
    @Value("${cbest.member.card.url:#{null}}")
    private String cardApi;
    @Value("${cbest.accessKey:#{null}}")
    private String accessKey;
    @Value("${cbest.member.score.info.url:#{null}}")
    private String scoreApi;
    @Value("${cbest.member.score.info.vjygs:#{null}}")
    private String vjygs;
    @Value("${cbest.member.score.info.vsyjh:#{null}}")
    private String vsyjh;

    @Autowired
    OrderReturnRepository returnRepository;
    @Value("${cbest.member.send.sale:#{null}}")
    private String sendSalesUrl;
    @Value("${cbest.member.crm.url:#{null}}")
    private String crmUrl;


    private Map buildHeader(){
        Map<String, String> header = new HashMap<>(2);
        header.put("Content-Type", "application/x-www-form-urlencoded");
        header.put("Signature", EncryptUtils.MD5(accessKey).toUpperCase());
        return header;
    }

    /**
     * 获取会员信息
     *
     * @param openId
     * @return
     */
    @Override
    public JSONObject getMemberInfo(String openId) {
        Assert.notNull(openId,"openId can not be null");
        if(logger.isDebugEnabled()){
            logger.debug(String.format("获取会员%s信息...",openId));
        }
        Map<String, String> param = new HashMap<>(2);
        param.put("openid", openId);
        String result = HttpClientUtil.doPostJson(infoApi, JSON.toJSONString(param), buildHeader());
        if(StringUtils.isNotEmpty(result)){
            JSONObject object = JSONObject.parseObject(result);
            if(logger.isDebugEnabled()){
                logger.debug(String.format("会员%s信息:%s",openId,object.toJSONString()));
            }
           return object;
        }
        if(logger.isDebugEnabled()){
            logger.debug(String.format("未获取到会员%s信息",openId));
        }
        return null;
    }

    /**
     * 获取动态会员卡
     * @param openId
     * @return
     */
    @Override
    public String getMemberCard(String openId) {
        Assert.notNull(openId,"openId can not be null");
        if(logger.isDebugEnabled()){
            logger.debug(String.format("获取会员%s动态会员卡...",openId));
        }
        Map<String, String> param = new HashMap<>(2);
        param.put("openid", openId);
        String result = HttpClientUtil.doPostJson(cardApi, JSON.toJSONString(param), buildHeader());
        if(StringUtils.isNotEmpty(result)){
            JSONObject object = JSONObject.parseObject(result);
            String errCode = object.getString("errCode");
            if(logger.isDebugEnabled()){
                logger.debug(String.format("会员%s动态会员卡:%s",openId,object.toJSONString()));
            }
            if(errCode.equals("0")){
                String trackNo = object.getString("data");
                if(StringUtils.isNotEmpty(trackNo)){
                    return trackNo;
                }
                logger.error("trackNo for openid:" +openId+" is empity");
                return null;
            }
            if(errCode.equals("1")){
                logger.info(object.getString("errMessage"));
                return null;
            }
            return null;
        }
        return null;
    }

    /**
     * 退货判断接口：返回差异积分
     *
     * @param judgeReturnRequest
     * @return
     */
    @Override
    public String getReturnScore(JudgeReturnRequest judgeReturnRequest) {
        if(logger.isDebugEnabled()){
            logger.debug(String.format("判断订单积分:%s",judgeReturnRequest.getVinvno()));
        }
        String result = HttpClientUtil.doPostJson(scoreApi, JSON.toJSONString(judgeReturnRequest), buildHeader());
        if(StringUtils.isNotEmpty(result)){
            if(logger.isDebugEnabled()){
                logger.debug(String.format("判断会员积分订单结果:%s",result));
            }
            return result;
        }
        logger.error("调用积分判断接口失败："+ scoreApi);
        return null;
    }

    /**
     * 退货判断接口：返回差异积分
     *
     * @param returnId
     * @return
     */
    @Override
    public String getReturnScoreForAdmin(Long returnId) {
        if(returnId != null){
            OrderReturn orderReturn = returnRepository.findOne(returnId);
            Order order = orderReturn.getRelatedOrder();
            MerchantStore store = order.getMerchantStore();
            if(store != null){
                JudgeReturnRequest request = new JudgeReturnRequest();
                request.setVmktcode(store.getExternalId());
                request.setVjygs(vjygs);
                request.setVsyjh(vsyjh);
                request.setVinvno(order.getOrderNumber());
                String result = getReturnScore(request);
                if(StringUtils.isNotEmpty(result)){
                    return result;
                }
            }
        }
        return null;
    }
    /**
     * 发送消费信息到积分系统
     *
     * @param msg
     * @return
     */
    @Override
    public JSONObject sendSales(Map msg) {
        if(logger.isDebugEnabled()){
            logger.debug(String.format("发送会员消费信息:%s",JSON.toJSONString(msg)));
        }
        Map<String, String> header = new HashMap<>(2);
        header.put("Content-Type", "application/x-www-form-urlencoded");
        header.put("Signature", DigestUtils.md5Hex(accessKey.getBytes()).toUpperCase());
        String resultContent = HttpClientUtil.doPostJson(sendSalesUrl, JSONObject.toJSONString(msg), header);
        if(logger.isDebugEnabled()){
            logger.debug(String.format("发送会员消费信息结果:%s",resultContent));
        }
        try {
            JSONObject jsonObject = JSON.parseObject(resultContent);
            return jsonObject;
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 会员系统发送验证短信
     *
     * @param method
     * @param openId
     * @param mobile
     * @param idNum
     * @param ppid
     * @return
     */
    @Override
    public JSONObject sendSms(String method, String openId, String mobile, String idNum, int ppid) {
        Map msg = new HashMap<String ,String>();
        msg.put("method",method);
        msg.put("openId",openId);
        msg.put("mobile",mobile);
        msg.put("idNum",idNum);
        msg.put("ppid",""+ppid);
        Map header = new HashMap();
        String resultContent = HttpClientUtil.doPost(crmUrl, msg,header);
        if(logger.isDebugEnabled()){
            logger.debug(String.format("会员注册系统请求参数：%s,会员注册系统返回:%s",msg,resultContent));
        }
        //添加cookie
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        if(request!=null){
           request.getSession().setAttribute(SessionConstant.SMS_COOKIE,header);
        }
        return JSON.parseObject(resultContent);
    }

    /**
     * 注册crm会员
     *
     * @param method     CreateCard
     * @param openId
     * @param name
     * @param mobile
     * @param idNum
     * @param verifyCode
     * @param publicid
     * @param ppid
     * @return
     */
    @Override
    public JSONObject register(String method, String openId, String name, String mobile, String idNum, String verifyCode, int publicid, int ppid) {
        Map msg = new HashMap<String ,String>();
        msg.put("method",method);
        msg.put("openId",openId);
        msg.put("mobile",mobile);
        msg.put("idNum",idNum);
        msg.put("name",name);
        msg.put("verifyCode",verifyCode);
        msg.put("publicid",""+publicid);
        msg.put("ppid",""+ppid);
        Map header = null;
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        if(request!=null){
            header =(Map) request.getSession().getAttribute(SessionConstant.SMS_COOKIE);
        }
        String resultContent = HttpClientUtil.doPost(crmUrl, msg,header);
        if(logger.isDebugEnabled()){
            logger.debug(String.format("注册crm会员:参数%s，结果%s",JSON.toJSONString(msg),resultContent));
        }
        return JSON.parseObject(resultContent);
    }

    /**
     * 绑定crm会员卡
     *
     * @param method     BindCard
     * @param openId
     * @param mobile
     * @param idNum
     * @param verifyCode
     * @param cardno
     * @param publicid
     * @param ppid
     * @return
     */
    @Override
    public JSONObject bind(String method, String openId, String mobile, String idNum, String verifyCode, String cardno, int publicid, int ppid) {
        Map msg = new HashMap<String ,String>();
        msg.put("method",method);
        msg.put("openId",openId);
        msg.put("mobile",mobile);
        msg.put("idNum",idNum);
        msg.put("cardno",cardno);
        msg.put("verifyCode",verifyCode);
        msg.put("publicid",""+publicid);
        msg.put("ppid",""+ppid);
        Map header = null;
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        if(request!=null){
            header =(Map) request.getSession().getAttribute(SessionConstant.SMS_COOKIE);
        }
        String resultContent = HttpClientUtil.doPost(crmUrl, msg,header);
        if(logger.isDebugEnabled()){
            logger.debug(String.format("绑定crm会员卡:%s",resultContent));
        }
        return JSON.parseObject(resultContent);
    }
}
